require 'sketchup.rb'
require 'open3'
require 'json'

# require File.join(__dir__, 'amtf_mixin.rb')
# require File.join(__dir__, '另存排版.rb') #不引入的话，htmldialog需要reload后才会响应
# require File.join(__dir__, 'A组件属性.rb')
pattern = File.join(__dir__, '*.rb')
puts pattern
Dir.glob(pattern).each { |file|
  Sketchup.require file
}

module AMTF
  # Sketchup.require(File.join(__dir__, '另存排版.rb'))

  unless file_loaded?(__FILE__)
    dialog_amtf_su=nil
    dialog_设置=nil
    @dialog=nil

    # menu = UI.menu('Plugins').add_submenu('amtf_su')
    # menu.add_item('amtf_su') {
    #   dialog_amtf_su.close if !dialog_amtf_su.nil?
    #   dialog_amtf_su=AMTF窗口.new()
    # }
    menu = UI.menu('Plugins')
    menu.add_item('amtf_su') {
      重启浏览器窗口(true)
      # self.主页
      # @dlg=AMTF::AMTF窗口.new
      # AMTF::AMTF窗口.new
      # @dialog=AMTF窗口.new()
      # if !@dialog.nil? && @dialog.visible?
      #   @dialog.bring_to_front
      # else
      #   @dialog=AMTF窗口.new()
      # end
      # @A组件属性obj=A组件属性.new()
    }
    # AMTF::reload
    file_loaded(__FILE__)
  end

  def self.重启浏览器窗口(显示)
    之前已经打开了窗口=false
    if !@dialog.nil? && @dialog.visible?
      之前已经打开了窗口=true
    end
    @dialog.close if !@dialog.nil?

    @dialog=AMTF窗口.new()
    # @dialog.set_size(100, 50)
    # @dialog.set_position(-500, -500)
    puts "之前已经打开了窗口"
    puts 之前已经打开了窗口
    if 之前已经打开了窗口
      puts "窗口置中！"
      @dialog.center
    end
    puts 显示
    # if 显示
    #   if RUBY_PLATFORM.index "darwin"
    #     @dialog.show_modal
    #   else
    #     @dialog.show
    #   end
    # else #不显示

    # end
  end
  def self.移动浏览器窗口()
    @dialog.set_position(500, -500)
  end

  class AMTF窗口about < UI::HtmlDialog
    def initialize
      options = {
        dialog_title: "关于amtf😄",
        preferences_key: "关于amtf😄",
        width: 600,
        height: 600,
        left: 300,
        top: 100,
        min_width: 50,
        min_height: 150,
        max_width: 1000,
        max_height: 1000,
        style: UI::HtmlDialog::STYLE_DIALOG
      }
      super(options)
      path = File.join(__dir__, '/关于amtf.html')
      set_file path
      observer=nil
      # Display the dialog box
      if RUBY_PLATFORM.index "darwin"
        show_modal
      else
        show
      end
    end
  end
  class AMTF窗口组件属性 < UI::HtmlDialog
    def initialize
      # Dialog parameters
      super "组件属性", false, "组件属性", 350, 600, 50, 100, true
      path = File.join(__dir__, '/组件属性.html')
      set_file path
      navigation_buttons_enabled = false
      min_width = 50
      min_height = 50
      # Display the dialog box
      if RUBY_PLATFORM.index "darwin"
        show_modal
      else
        show
      end
    end
  end

  class AMTF窗口 < UI::HtmlDialog
    include AMTF_mixin
    def initialize
      # Dialog parameters
      # super "amtf", false, "amtf", 350, 600, 50, 100, true
      # puts File.join(__dir__, '另存排版.rb')
      options = {
        dialog_title: "amtf",
        preferences_key: "amtf",
        # scrollable: false,
        # resizable: false,
        width: 400,
        height: 160,
        left: 0,
        top: 100,
        # min_width: 50,
        # min_height: 150,
        max_width: 1000,
        max_height: 1000,
        # style: UI::HtmlDialog::STYLE_DIALOG
        style: UI::HtmlDialog::STYLE_UTILITY
      }
      super(options)
      path = File.join(__dir__, '/amtf_su.html')
      set_file path
      # set_url('https://www.baidu.com/')
      # set_url("http://127.0.0.1:5501")
      observer=nil
      # Display the dialog box
      if RUBY_PLATFORM.index "darwin"
        show_modal
      else
        show
      end

      @A组件属性obj=A组件属性.new()

      add_action_callback("识别选中组件") {|dialog, arg|
        # puts "收到的组件名："+arg
        动态属性h=@A组件属性obj.识别选中组件()
        # puts "aaa"
        # puts 动态属性h.to_json
        execute_script("接收识别选中组件('#{动态属性h.to_json}')")
      }
      add_action_callback("修改组件属性") {|dialog, arg|
        # puts arg
        修改组件属性结果=@A组件属性obj.修改组件属性(arg)
        execute_script("接收修改组件属性('#{修改组件属性结果.to_json}')")
      }

      # Set the WebDialog's callback
      add_action_callback("开启显示边界框尺寸") {|dialog, arg|
        puts "收到的arg："+arg
        if arg=="true"
          if observer==nil
            puts "创建观察者"
            observer=A选择对象观察者.new(self)
          else
            puts "已经创建过了观察者"
          end
          Sketchup.active_model.selection.add_observer(observer)
        else
          if observer!=nil
            selection = Sketchup.active_model.selection
            status = selection.remove_observer observer
            puts "移除观察者"
            puts status
          else
            puts "本来就没有观察者"
          end
        end
      }

      add_action_callback("拼合组件名") {|dialog, arg|
        puts "收到的组件名："+arg
        A导出.new().拼合组件名(arg)
      }

      add_action_callback("解读组件名") {|dialog, arg|
        # 对象=返回第一个选择对象
        # puts "对象.name"+对象.name
        解读后的组件名=A导出.new().解读组件名
        # 发送解读后的组件名(解读后的组件名)
        self.execute_script("接收解读后的组件名('#{解读后的组件名}')")
      }
      add_action_callback("发送调试模式") {|dialog, arg|
        # amtf_dxf文件='D:\amtf\amtf_csharp\amtf_dxf\bin\Debug\netcoreapp3.1/amtf_dxf.exe'
        if arg!="false"
          puts "是调式模式"
          @调式模式=true
        else
          puts "非调式模式"
          @调式模式=false
        end
      }
      add_action_callback("隐藏本窗口") {|dialog, arg|
        AMTF::移动浏览器窗口
        # dialog.set_position(500, -500)
      }
      add_action_callback("开启amtf_su_ui") {|dialog, arg|
        # exists1 = File::exists?("D:\百度云\text.txt")
        arg = arg.gsub!(/\\/, "/")
        # amtf_dxf文件='D:\amtf\amtf_web\amtf_su_ui\dist\electron\Packaged\amtf_su_ui-win32-x64/amtf_su_ui.exe'
        amtf_dxf文件=arg +'/amtf_su_ui.exe'
        exists1 = File::exists?(amtf_dxf文件)
        if exists1
          kk=Open3.popen3(amtf_dxf文件)
          puts "调用外部命令结果："
          puts kk
          AMTF::重启浏览器窗口(true)
        else
          result = UI.messagebox("文件不存在！\n#{amtf_dxf文件}")
        end

      }
      add_action_callback("开启amtf_dxf") {|dialog, arg|
        A导出.new().显示不能隐藏的层()

        判断是否调试模式
        if @调式模式
          amtf_dxf文件='D:\amtf\amtf_csharp\amtf_dxf\bin\Debug\netcoreapp3.1/amtf_dxf.exe'
        else
          # amtf_dxf文件='../../amtf_dxf/amtf_dxf.exe'
          # amtf_dxf文件=File.join(__dir__, '/amtf_dxf/amtf_dxf.exe')
          amtf_dxf文件='amtf_dxf.exe'
        end
        # exec 'D:\amtf\amtf_csharp\amtf_dxf\bin\Debug\netcoreapp3.1/amtf_dxf.exe'
        # system(amtf_dxf文件)
        # `D:\amtf\amtf_csharp\amtf_dxf\bin\Debug\netcoreapp3.1/amtf_dxf.exe`
        kk=Open3.popen3(amtf_dxf文件)
        puts "调用外部命令结果："
        puts kk
      }
      # add_action_callback("开启amtf_dxf") {|dialog, arg|
      #   调用amtf_dxf('D:\amtf\00南腾家居-项目\导出20221016_202614/吊柜-顶板#18__1_24_00_1_-1___amtf_板厚292.dxf')
      # }
      add_action_callback("关于amtf") {|dialog, arg|
        puts "AMTF::AMTF窗口about.newkk"
        # AMTF窗口about.new
        # AMTF::AMTF窗口about.new
        link=File.join(__dir__, '关于amtf.html')
        # system("start #{link}")
        kk=Open3.popen3("start #{link}")
      }
      # add_action_callback("导出cad") {|dialog, arg|
      #   puts arg
      #   arg_sp=arg.split("|")
      #   # puts arg_sp
      # }

      add_action_callback("导出cad") {|dialog, arg|
        puts arg
        arg_sp=arg.split("_板数")
        封边信息=arg_sp[0]
        每块板数=arg_sp[1]

        # 生产 = JSON.parse(arg)
        # 每块板数=生产[:每块板数]

        # Sketchup.active_model.save
        导出=A导出.new()
        发送提示信息("导出组件到单独文件中，稍安勿躁~~" )
        拟导出全名hash,导出路径=导出.另存skp放平炸开重组组件_导出组件定义到单独文件(每块板数)
        计数=1
        拟导出全名hash.each {|k,v|
          导出全名=k
          原缩放大小=v
          导出dxf全名,板厚mm=导出.导出dxf(导出全名)
          发送提示信息("转amtf_dxf处理，注意看其进度……" )
          # amtf.nil
          # kk=调用amtf_dxf(导出dxf全名+"|"+计数.to_s+"|"+封边信息)
          # kk=调用amtf_dxf("#{导出dxf全名}|#{板厚mm}|#{计数}|#{封边信息}")

          导出dxf全名="#{导出dxf全名}|#{板厚mm}|#{计数}|#{封边信息}"
          导出dxf全名 = 导出dxf全名.gsub!(/\\/, "/")
          puts "导出dxf全名"
          puts 导出dxf全名
          # amtf.nil
          # 生产[:导出dxf全名]=导出dxf全名
          # 生产[:板厚mm]=板厚mm
          # 生产[:计数]=计数
          # puts "调用amtf_dxf2('#{生产.to_json}')"
          self.execute_script("调用amtf_dxf2('#{导出dxf全名}')")
          计数 += 1
          # puts "调用amtf_dxf(导出dxf全名):#{kk}"
        }
        result = UI.messagebox('导出完成，是否 需要 打开导出 文件夹？', MB_YESNO)
        if result == IDYES
          # system('D:\amtf\amtf_csharp\amtf_dxf\bin\Debug\netcoreapp3.1/amtf_dxf.exe')
          UI.openURL(导出路径)
          Open3.popen3("CopyClip.exe '#{导出路径}'")

        end
      }

      add_action_callback("孤立") {|dialog, arg|
        # puts "amtf"
        AF另存排版.new().孤立()
      }
      add_action_callback("选择同材质组件") {|dialog, arg|
        # puts "amtf"
        AF另存排版.new().选择同材质组件()
      }
      add_action_callback("移除组件边面材质") {|dialog, arg|
        # puts "amtf"
        AF另存排版.new().移除组件边面材质()
      }
      add_action_callback("更改背板厚度") {|dialog, arg|
        puts arg
        AF另存排版.new().更改背板厚度(arg)
      }

      add_action_callback("测试") {|dialog, arg|
          # puts arg
          # 联系amtf
          # 测试连接
          # 对象=返回第一个选择对象()
          # A导出.new().删除参考线(对象)

          # 设置常用对象
          # A导出.new().内部边界转子群组(@model)

          # A导出.new().焊接组件边线(对象)
          # A导出.new().导出v2
          # A组件属性.new().遍历组件属性
          # AMTF窗口组件属性.new
          reload其他插件

          发送提示信息("方法完成")
      }

      add_action_callback("刷新amtf") {|dialog, arg|
        AMTF::reload
        # puts arg+" 完成！"
        Sketchup::set_status_text arg+" 完成！"
        # return arg+" 完成！"
      }
      add_action_callback("匹配尺寸") {|dialog, arg|
        Sketchup.active_model.select_tool A匹配尺寸.new
      }
      add_action_callback("对齐") {|dialog, arg|
        # Sketchup.active_model.select_tool( AF对齐.new )
        Sketchup.active_model.select_tool AF对齐.new
      }
      add_action_callback("多余组件处理") {|dialog, arg|
        AF另存排版.new().多余组件处理
      }
      add_action_callback("画柜子") {|dialog, arg|
        # p "hello"
        Sketchup.active_model.select_tool AF画柜子.new(arg+".skp")
      }
      add_action_callback("另存为排版模型") {|dialog, arg|
        AF另存排版.new().另存为排版模型
      }
      add_action_callback("删除指定图层") {|dialog, arg|
         Sketchup::set_status_text __method__.to_s()+" ing"
        AF另存排版.new().删除指定图层
      }
      add_action_callback("删除隐藏项目") {|dialog, arg|
        AF另存排版.new().删除隐藏项目不传参数
      }
      add_action_callback("删除or炸开无板字组件") {|dialog, arg|
        AF另存排版.new().删除or炸开无板字组件
      }
      add_action_callback("炸开所有子组件") {|dialog, arg|
        AF另存排版.new().炸开所有子组件
      }
      add_action_callback("组件改名") {|dialog, arg|
        AF另存排版.new().组件改名
      }
      add_action_callback("组件转群组") {|dialog, arg|
        AF另存排版.new().组件转群组
      }
      add_action_callback("干涉检查") {|dialog, arg|
        AF另存排版.new().干涉检查
      }
      add_action_callback("一键排版预处理") {|dialog, arg|
        AF另存排版.new().一键排版预处理
      }
      add_action_callback("延伸背板") {|dialog, arg|
        AF另存排版.new().延伸背板(arg)
      }

      add_action_callback("文件改名") {|dialog, arg|
        文件改名("kk")
      }
      add_action_callback("返回值给ruby") {|dialog, arg|
        return arg
      }
      add_action_callback("清除未使用") {|dialog, arg|
        清除未使用
      }
      add_action_callback("重载ABF") {|dialog, arg|
        Sketchup::set_status_text "重载ABF"+" ing"

        path = Sketchup.find_support_file "abf_solutions/startup.rb", "Plugins"
        puts "path=" + path.to_s
        load path.to_s
        puts "重新加载ABFing……稍安勿躁……"
        Sketchup::set_status_text "重载ABF"+" 完成"
      }
      # Display the dialog box
      # if RUBY_PLATFORM.index "darwin"
      #   show_modal
      # else
      #   show
      # end

    end #initialize

    def reload其他插件
      puts "reload其他插件ing"
      original_verbose = $VERBOSE
      $VERBOSE = nil
      # pattern = File.join('D:/amtf/amtf_suoc/', 'oneclickcabinet/**/*.rb')
      pattern = File.join('D:/amtf/amtf_suoc/', '*.rb')
      puts pattern
      Dir.glob(pattern).each { |file|
        # Cannot use `Sketchup.load` because its an alias for `Sketchup.require`.
        # puts file
        load file
      }.size
      ensure
        $VERBOSE = original_verbose
    end


    # 执行网页js👇
    def 调用amtf_dxf(导出dxf全名)
      # phone = %q|D:\amtf\00南腾家居-项目\导出20221016_202614/吊柜-顶板#18__1_24_00_1_-1___amtf_板厚292.dxf|
      # # puts "电话号码 : #{phone}"

      # # 移除数字以外的其他字符
      # phone = phone.gsub!(/\\/, %q|\\\\\\\\|)
      # puts "电话号码 : #{phone}"

      # 导出dxf全名 = 导出dxf全名.gsub!(/\\/, "\\\\\\\\")
      导出dxf全名 = 导出dxf全名.gsub!(/\\/, "/")
      puts "调用amtf_dxf('#{导出dxf全名}')"

      self.execute_script("调用amtf_dxf('#{导出dxf全名}')")
      # self.execute_script("调用amtf_dxf('D:amtf00南腾家居-项目')")
      # D:\amtf\00南腾家居-项目\导出20221016_202614/吊柜-顶板#18__1_24_00_1_-1___amtf_板厚292.dxf
    end

    def 判断是否调试模式()
      self.execute_script("发送调试模式()")
    end
    # def 发送解读后的组件名(解读后的组件名)
    #   self.execute_script("接收解读后的组件名('#{解读后的组件名}')")
    # end

    def 显示边界框尺寸(边界框尺寸)
      puts "边界框尺寸"
      puts 边界框尺寸
      self.execute_script("显示边界框尺寸('#{边界框尺寸}')")
    end

  end #AMTF窗口





end # module amtf_su
